package jchat.genral;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import jchat.Controller.LocalStorageHandler;
import jchat.interfaces.IAppManager;
import jchat.services.IMService;
import jchat.types.FriendInfo;
import jchat.types.MessageInfo;
import jchat.types.Session;
import chat.jdaas.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
//import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class SendIamge extends Activity implements OnClickListener{
	private Button btn_cancle,btn_sendmedia;
	private IAppManager imService;
	private String settingsTAG = "AppNameSettings";
	private SharedPreferences prefs;
	 private ImageView img;
	    private String imagepath=null;
	    ProgressDialog simpleWaitDialog;
	    Bundle extra; 
	    String name=null;
	    String password=null;
	   // private IAppManager imService;
	private Handler handler = new Handler();
	private LocalStorageHandler localstoragehandler;
	private FriendInfo friend = new FriendInfo();
private ServiceConnection mConnection = new ServiceConnection() {
      
		
		
		public void onServiceConnected(ComponentName className, IBinder service) {          
            imService = ((IMService.IMBinder)service).getService();
        }
        public void onServiceDisconnected(ComponentName className) {
        	imService = null;
            Toast.makeText(SendIamge.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };
	protected void  onCreate(Bundle saveinvt) {
		super.onCreate(saveinvt);
		setContentView(R.layout.sendmedia);
		try
		{
		btn_cancle=(Button)findViewById(R.id.btn_cancle);
		btn_sendmedia=(Button)findViewById(R.id.btn_sendmedia);
		img=(ImageView)findViewById(R.id.sendimageview);
		btn_sendmedia.setOnClickListener(this);
		btn_cancle.setOnClickListener(this);
		localstoragehandler =new LocalStorageHandler(this);
        Bundle extras = this.getIntent().getExtras();
		
		friend.userKey=extras.getString(FriendInfo.USER_KEY);
		friend.userName = extras.getString(FriendInfo.USERNAME);
		 prefs = getSharedPreferences(settingsTAG, 0);
         this.name = prefs.getString(Session.Username, "");
		this.password=prefs.getString(Session.PASSWORD, "");
		setTitle("Send Image"+friend.userName);
		
		}
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0==btn_sendmedia)
		{
			
			
			// mess
                      try
                      {
                    	  //storeImage(bitmap,"today.jpg");
                    	  localstoragehandler.insert(name, friend.userKey, imagepath, true, "image");
                      new ImageUploaderTask().execute(imagepath);
                    	 SendIamge.this.finish();
                      	
                      }
                      catch(Exception e)
                      {
                    	  Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                      }
                   
			Toast.makeText(getApplicationContext(), "sendmedia", Toast.LENGTH_LONG).show();
		}
		else if(arg0==btn_cancle)
		{
			Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
			Toast.makeText(getApplicationContext(), "cancle", Toast.LENGTH_LONG).show();
		}
	}
	
	 @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		    
	    	if (requestCode == 1 && resultCode == RESULT_OK) {
	            //Bitmap photo = (Bitmap) data.getData().getPath(); 
	          
	            Uri selectedImageUri = data.getData();
	            imagepath = getPath(selectedImageUri);
	            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
	            img.setImageBitmap(bitmap);
	           // messageText.setText("Uploading file path:" +imagepath);
	            
		    	
		    }
	    }
	    	 public String getPath(Uri uri) {
	    	        String[] projection = { MediaStore.Images.Media.DATA };
	    	        Cursor cursor = managedQuery(uri, projection, null, null, null);
	    	        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    	        cursor.moveToFirst();
	    	        return cursor.getString(column_index);
	    	    }
	    	 private boolean storeImage(Bitmap imageData, String filename) {
	    			//get path to external storage (SD card)
	    			String iconsStoragePath = Environment.getExternalStorageDirectory() + "/JChat/myImages/Sent";
	    			File sdIconStorageDir = new File(iconsStoragePath);

	    			//create storage directories, if they don't exist
	    			sdIconStorageDir.mkdirs();

	    			try {
	    				String filePath = sdIconStorageDir.toString() + filename;
	    				FileOutputStream fileOutputStream = new FileOutputStream(filePath);

	    				BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

	    				//choose another format if PNG doesn't suit you
	    				imageData.compress(CompressFormat.PNG, 100, bos);

	    				bos.flush();
	    				bos.close();

	    			} catch (FileNotFoundException e) {
	    				Log.w("TAG", "Error saving image file: " + e.getMessage());
	    				return false;
	    			} catch (IOException e) {
	    				Log.w("TAG", "Error saving image file: " + e.getMessage());
	    				return false;
	    			}

	    			return true;
	    		}	
	    		
	@Override
	protected void onResume() {
		super.onResume();
		bindService(new Intent(SendIamge.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
		   
		
	}
	
	@Override
	protected void onPause() 
	{
		unbindService(mConnection);
		super.onPause();
	}

private class ImageUploaderTask extends AsyncTask<String, Integer, Void> {
		
		@Override
		protected void onPreExecute(){
			simpleWaitDialog = ProgressDialog.show(SendIamge.this, "Wait", "Uploading Image");
		}
		
		@Override
		protected Void doInBackground(String... params) {
			new ImageUploadUtility().uploadSingleImage(params[0],SendIamge.this.name,SendIamge.this.password,SendIamge.this.friend.userKey);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result){
			//super.onPostExecute(result);
			simpleWaitDialog.dismiss();
			
		}
	}

  	  
  	 
}
